﻿﻿//------------------------------------------------------------------------------
// <copyright file="Common.cs" company="Microsoft">
//
//      Copyright 2013 Microsoft Corporation 
//
//      Licensed under the Microsoft Public License (Ms-PL). 
//      You may not use this file except in compliance with the License.
//
//      Unless required by applicable law or agreed to in writing, software 
//      distributed under the License is distributed on an "AS IS" BASIS,
//      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
//      See the License for the specific language governing permissions and 
//      limitations under the License. 
//
// </copyright>
﻿//------------------------------------------------------------------------------

namespace MyOpenXmlColumnWidth
{
    using System;
    using System.Linq;
    using DocumentFormat.OpenXml.Spreadsheet;

    public class MyColumnWidth
    {
        public static void SetColumnWidth(uint columnIndex, decimal width, Worksheet openXmlWorksheet)
        {
            var columns = openXmlWorksheet.GetFirstChild<Columns>();
            if (columns == null)
            {
                columns = new Columns();
                OpenXmlHelper.Common.AppendChild(typeof(Columns), columns, openXmlWorksheet);
            }

            var column = columns.ChildElements.FirstOrDefault(t => (t is Column) && (t as Column).Min <= columnIndex && (t as Column).Max <= columnIndex) as Column;

            if (column == null)
            {
                column = new Column()
                {
                    Min = columnIndex,
                    Max = columnIndex
                };

                columns.Append(column);
            }

            column.CustomWidth = true;
            column.Width = Convert.ToDouble(width);
        }
    }
}
